# -*- coding: utf-8 -*-
from django.core.management.base import NoArgsCommand
import urllib2
from djwatch.models import Server, Task, Check, CheckError
import socket

socket.setdefaulttimeout(30)

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        for server in Server.objects.filter(enabled=True):
            Task.objects.get_or_create(server=server)

        while True:
            try:
                task = Task.objects.all()[0]
            except IndexError:
                break
            get_stat(task.server)
            task.delete()

def get_stat(server):
    url = 'http://%s:%d' % (server.host, server.agent_port)
    try:
        print (u'%s...' % url).encode('utf-8'),
        content = urllib2.urlopen(url).read()
    except Exception, e:
        print 'error'
        CheckError.objects.create(server=server, error=e.message)
    else:
        print 'done'
        Check.objects.create(server=server, data=content)
